<script setup lang="ts">
import { ref } from 'vue'
import { message } from 'ant-design-vue'
import * as imApi from '@/api/im'

const myModal = ref()

let theTitle = ref<string>('关联微信账号')
let onlyType = ref<string>('wx')

let paramCustomerId = ref<string>()
const showModal = (id: string, type = 'wx') => {
  selectedRowKey.value = []
  selectedRow.value = []

  onlyType.value = type
  if(onlyType.value == 'wx'){
    theTitle.value = '关联微信账号'
  }else {
    theTitle.value = '关联闲鱼账号'
  }

  paramCustomerId.value = id
  myModal.value?.showModal()
  getList()
}

const emit = defineEmits<{
  refresh: []
}>()

defineExpose({
  showModal,
})

const dataSource = ref<Array<any>>([])
const columns = [
  {
    key: 'id',
    width: 130,
  },
  {
    title: '头像',
    key: 'avatar',
    width: 130,
  },
  {
    title: '微信昵称',
    key: 'wxName',
    width: 150,
  },
  {
    key: 'fishId',
    width: 150,
  },
]

interface SearchParams {
  channel: number
  nickName?: string | undefined
  robotId?: string | undefined
  wechatId?: string | undefined
  fishId?: string | undefined
}
const searchParams = ref<SearchParams>({
  channel: 1,
})

// 表格多选
const selectedRowKey = ref<Array<any>>([])
const selectedRow = ref<Array<object>>([])
const onSelectChange = (selectedRowKeys: any[], selectedRows: any[]) => {
  selectedRowKey.value = selectedRowKeys
  selectedRow.value = selectedRows
}
const getCheckboxProps = (record: any) => ({
  disabled: record.customerId !== '0',
})

const getList = async () => {
  searchParams.value.channel = onlyType.value == 'wx' ? 1 : 3 // 1:微信，3：闲鱼,
  try {
    let { state, data, message: msg } = await imApi.getRelevanceRobot(searchParams.value)
    if (state === 200) {
      if (searchParams.value.channel === 1) {
        dataSource.value = data.wechatRobotList
      } else if (searchParams.value.channel === 3) {
        dataSource.value = data.fishRobotList
      }
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

// 查询
const formRef = ref()
interface FormState {
  nickName?: string | undefined
  robotId?: string | undefined
  wechatId?: string | undefined
  fishId?: string | undefined  
}
const formState = reactive<FormState>({})
const search = () => {
  // pagination.value.current = 1
  // searchParams.value.currentPage = 1
  formRef.value.validate().then(() => {
    searchParams.value.nickName = formState.nickName || ''
    searchParams.value.robotId = formState.robotId || ''
    searchParams.value.wechatId = formState.wechatId || ''
    searchParams.value.fishId = formState.fishId || ''
    getList()
  })
}

// 重置
const reset = () => {
  formRef.value.resetFields()
  Reflect.deleteProperty(searchParams.value, 'nickName')
  Reflect.deleteProperty(searchParams.value, 'robotId')
  Reflect.deleteProperty(searchParams.value, 'wechatId')
  Reflect.deleteProperty(searchParams.value, 'fishId')
  getList()
}

// 绑定
const okBind = async () => {
  const params = {
    channel: onlyType.value == 'wx' ? 1 : 3, // 1:微信，3：闲鱼,
    customerId: paramCustomerId.value,
    robotIds: selectedRowKey.value,
  }
  try {
    let { state, message: msg } = await imApi.customerRelevanceRobot(params)
    if (state === 200) {
      message.success('关联成功')
      emit('refresh')
      myModal.value.cancelModal()
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}
</script>

<template>
  <MyModal ref="myModal" :title="theTitle" :top="20" :width="950">
    <template #content>
      <div class="searchBox">
        <a-form ref="formRef" layout="inline" :model="formState">
          <a-form-item label="昵称" name="nickName">
            <a-input v-model:value="formState.nickName" style="width: 150px" />
          </a-form-item>

          <a-form-item label="账号ID" name="robotId">
            <a-input v-model:value="formState.robotId" style="width: 150px" />
          </a-form-item>

          <a-form-item v-if="onlyType == 'wx'" label="微信ID" name="wechatId">
            <a-input v-model:value="formState.wechatId" style="width: 150px" />
          </a-form-item>

          <a-form-item v-if="onlyType == 'LdleFish'" label="闲鱼ID" name="fishId">
            <a-input v-model:value="formState.fishId" style="width: 150px" />
          </a-form-item>
        </a-form>
        <a-button type="primary" style="border-radius: 6px" @click="search">
          <template #icon><SearchOutlined /></template>
          搜索
        </a-button>
        <a-button @click="reset" style="border-radius: 6px">重置</a-button>
      </div>

      <a-table
        style="overflow-x: scroll"
        :columns="columns"
        :data-source="dataSource"
        :pagination="false"
        rowKey="id"
        :row-selection="{
          selectedRowKeys: selectedRowKey,
          onChange: onSelectChange,
          getCheckboxProps: getCheckboxProps,
        }"
        :scroll="{ y: 300 }"
      >
        <template #emptyText>
          <a-empty description="暂无数据" />
        </template>

        <template #headerCell="{ column }">
          <template v-if="column.key === 'fishId'">
            <span v-if="onlyType == 'wx'">微信ID</span>
            <span v-if="onlyType == 'LdleFish'">闲鱼ID</span>
          </template>
          <template v-else-if="column.key === 'id'">
            <span v-if="onlyType == 'wx'">账号ID</span>
            <span v-if="onlyType == 'LdleFish'">账号ID</span>
          </template>
          <template v-else-if="column.key === 'wxName'">
            <span v-if="onlyType == 'wx'">微信昵称</span>
            <span v-if="onlyType == 'LdleFish'">闲鱼昵称</span>
          </template>
        </template>

        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'id'">
            <span>{{ record.id }}</span>
          </template>

          <template v-else-if="column.key === 'avatar'">
            <a-popover placement="rightTop">
              <template #content>
                <div class="popoverImg">
                  <img :src="record.avatar" alt="" />
                </div>
              </template>
              <div class="imgBox">
                <img :src="record.avatar" alt="获取失败..." />
              </div>
            </a-popover>
          </template>

          <template v-if="column.key === 'wxName'">
            <span>{{ record.nickName }}</span>
          </template>

          <template v-if="column.key === 'fishId'">
            <span v-if="onlyType == 'wx'">{{ record.wechatId }}</span>
            <span v-if="onlyType == 'LdleFish'">{{ record.fishId }}</span>
          </template>
        </template>
      </a-table>

      <div style="text-align: right">
        <a-button @click="myModal.cancelModal()" style="border-radius: 6px">取消</a-button>
        <a-button @click="okBind" style="margin-left: 10px; border-radius: 6px" type="primary">
          确定进行关联
        </a-button>
      </div>
    </template>
  </MyModal>
</template>

<style scoped lang="less">
.searchBox {
  margin-bottom: 10px;
  display: flex;

  input {
    width: 200px;
    margin-right: 10px;
  }

  button {
    margin-right: 10px;
  }
}

.imgBox {
  width: 50px;
  height: 50px;

  img {
    height: 50px;
  }
}

.popoverImg {
  width: 50px;
  img {
    width: 100%;
  }
}
</style>
